package api

import (
	"g_ansible/ansible/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

type HostApi struct {
}

func (h *HostApi) QueryHandler(c *gin.Context) {
	// 调用原始 Query 函数获取数据
	groups := hostService.Query()

	// 返回 JSON 响应
	c.JSON(http.StatusOK, groups)
}

func (h *HostApi) AddHandler(c *gin.Context) {
	var g model.V1Group
	err := c.ShouldBindJSON(&g)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if g.Name == "" {
		c.JSON(400, gin.H{"error": "缺少必要的参数: group"})
		return
	}

	for _, host := range g.Host {
		if host.AnsibleHost == "" || host.AnsibleSshUser == "" || host.AnsiblePort == 0 || host.AnsibleSshPass == "" {
			c.JSON(400, gin.H{"error": "缺少必要的参数"})
			return
		}

	}
	//查询是否存在
	if hostService.IsHostExist(g) {
		c.JSON(400, gin.H{"error": "host已存在"})
		return
	}

	err = hostService.Add(g)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": "添加成功"})
}

func (h *HostApi) DeleteHandler(c *gin.Context) {
	// 获取要删除的主机信息
	var groupName, hostAlias string

	// 检查是否通过路径参数传递
	groupName = c.Param("group")
	hostAlias = c.Param("host")

	// 如果路径参数为空，则检查查询参数
	if groupName == "" || hostAlias == "" {
		groupName = c.Query("group")
		hostAlias = c.Query("host")
	}

	// 检查参数是否完整
	if groupName == "" || hostAlias == "" {
		c.JSON(400, gin.H{"error": "缺少必要的参数: group 和 host"})
		return
	}

	// 调用service层的删除方法
	err := hostService.Delete(groupName, hostAlias)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, gin.H{"message": "删除成功"})
}
